package top.huntwolf.admin.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.show.api.ShowApiRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.dao.*;
import top.huntwolf.admin.exception.ServiceException;
import top.huntwolf.admin.listener.BookExcelListener;
import top.huntwolf.admin.pojo.orderEntity.Order;
import top.huntwolf.admin.pojo.orderEntity.OrderBook;
import top.huntwolf.admin.pojo.Subject;
import top.huntwolf.admin.pojo.book.Book;
import top.huntwolf.admin.pojo.book.BuyBook;
import top.huntwolf.admin.pojo.book.SaleBook;
import top.huntwolf.admin.pojo.excel.BookExcelData;
import top.huntwolf.admin.utils.RedisUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BookService {

    @Autowired
    private BookDao bookDao;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private HotSaleDao hotSaleDao;

    @Autowired
    private SubjectDao subjectDao;

    @Autowired
    private BookReserveService reserveService;

    @Autowired
    private BookStorageService storageService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${showApi.url1}")
    private String url1;

    @Value("${showApi.url2}")
    private String url2;

    @Value("${showApi.appid}")
    private String appid;

    @Value("${showApi.secret}")
    private String secret;

    // 按ISBN查找
    public BuyBook searchBookByISBN(String isbn) {
        BuyBook book = bookDao.selectBookByISBNAndReserve(isbn);
        if (book == null) {
            throw new ServiceException(CodeMsg.NOT_BUY_BOOK.fillArgs("书店没有此书"));
        } else {
//            System.out.println(book);
            // 如果数据库有，则在subject中更新搜索次数
            subjectService.addSort(book.getSubjectId());
        }
        return book;

    }


    // 按ISBN查找，并添加数据库
    public SaleBook addSaleBookByISBN(String isbn) {
//        Book book = bookDao.selectBookByISBNAndReserve(isbn);
//        if (book == null) {
//            //如果数据库没有则发请求
//            String res = new ShowApiRequest(url1, appid, secret)
//                    .addTextPara("isbn", isbn)
//                    .post();
//            JSONObject resJson = JSON.parseObject(res);
//            if (resJson.get("showapi_res_code").equals(0)) {
//                //请求成功
////                System.out.println(resJson.getJSONObject("showapi_res_body").getString("ret_code"));
//                if (!resJson.getJSONObject("showapi_res_body").getString("ret_code").equals("0")) {
//                    //接口返回的错误信息
//                    String remark = resJson.getJSONObject("showapi_res_body").getString("remark");
////                    System.out.println(remark);
//                    throw new ServiceException(CodeMsg.SHOWAPI_ERROR.fillArgs(remark));
//                }
//                //查询成功
//                book = new SaleBook();
//                JSONObject resBook = resJson.getJSONObject("showapi_res_body").getJSONArray("datas").getJSONObject(0);
//                book.setIsbn(isbn);
//                book.setSeries(resBook.getString("series"));
//                book.setTitle(resBook.getString("title"));
//                book.setImg(resBook.getString("img"));
//                book.setSmallImg(resBook.getString("smallimg"));
//                book.setPrice(resBook.getString("price"));
//                book.setAuthor(resBook.getString("author"));
//                book.setPublisher(resBook.getString("publisher"));
//                book.setPubDate(resBook.getString("pubdate"));
//                book.setPubPlace(resBook.getString("pubplace"));
//                book.setBinding(resBook.getString("binding"));
//                book.setGenus(resBook.getString("genus"));
//                book.setFormat(resBook.getString("format"));
//                book.setPage(resBook.getString("page"));
//                book.setWordNum(resBook.getString("wordnum"));
//                book.setEdition(resBook.getString("edition"));
//                book.setYinci(resBook.getString("yinci"));
//                book.setPaper(resBook.getString("paper"));
//                book.setLanguage(resBook.getString("language"));
//                book.setKeyword(resBook.getString("keyword"));
//                book.setBookCatalog(resBook.getString("bookcatalog"));
//                book.setGist(resBook.getString("gist"));
//                book.setCipTxt(resBook.getString("ciptxt"));
//                //加入到数据库中
//                bookDao.insertSaleBook(book);
//            } else {
//                //接口返回的错误信息
//                String error = resJson.getString("showapi_res_error");
//                throw new ServiceException(CodeMsg.SHOWAPI_ERROR.fillArgs(error));
//            }
//        }else if(bookDao.selectSaleBookByISBN(isbn)==null) {
//            bookDao.insertSaleBook(book);
//        }
//        SaleBook saleBook = (SaleBook) book;
//        return saleBook;
        return null;
    }

    public List<BuyBook> searchBookOrderSaleDesc(String searchField,int pageNum){
        PageHelper.startPage(pageNum,20);
        List<BuyBook> books = bookDao.selectBookBySearchFieldOrderSaleDesc(searchField);
        checkBooksIsEmpty(books);
        for(BuyBook book : books){
            if(pageNum==1) {
                book.setSearchTime(1);
                bookDao.IncreaseSearchTime(book);
            }
        }
        return checkMaxPage(pageNum,books);
    }



    public List<BuyBook> searchBookOrderSaleAsc(String searchField,int pageNum){
        PageHelper.startPage(pageNum,20);
        List<BuyBook> books = bookDao.selectBookBySearchFieldOrderSaleAsc(searchField);
        checkBooksIsEmpty(books);
        return checkMaxPage(pageNum,books);
    }

    public List<BuyBook> searchBookOrderPriceDesc(String searchField,int pageNum){
        PageHelper.startPage(pageNum,20);
        List<BuyBook> books = bookDao.selectBookBySearchFieldOrderPriceDesc(searchField);
        checkBooksIsEmpty(books);
        return checkMaxPage(pageNum,books);
    }

    public List<BuyBook> searchBookOrderPriceAsc(String searchField,int pageNum){
        PageHelper.startPage(pageNum,20);
        List<BuyBook> books = bookDao.selectBookBySearchFieldOrderPriceAsc(searchField);
        checkBooksIsEmpty(books);
        return checkMaxPage(pageNum,books);
    }

    public List<BuyBook> searchBookBySubjectOrderSaleDesc(Integer id,int pageNum) {

        Subject subject = subjectDao.findSubjectBySubjectId(id);
        List<BuyBook> bookList;
        PageHelper.startPage(pageNum,20);
        if(subject.getParentId()==0){
            bookList = bookDao.selectBookByParentSubjectOrderSaleDesc(id);
        }
        else{
            bookList = bookDao.selectBookBySubjectOrderSaleDesc(id);
        }
        if (bookList.size() == 0) {
            throw new ServiceException(CodeMsg.NON_FIND_SUBJECT);
        } else {
            // 搜索之后添加搜索次数
            if(pageNum==1)
            subjectService.addSort(id);
            return checkMaxPage(pageNum,bookList);
        }

    }

    public List<BuyBook> searchBookBySubjectOrderSaleAsc(Integer id,int pageNum) {
        Subject subject = subjectDao.findSubjectBySubjectId(id);
        List<BuyBook> bookList;
        PageHelper.startPage(pageNum,20);
        if(subject.getParentId()==0){
            bookList = bookDao.selectBookByParentSubjectOrderSaleAsc(id);
        }
        else{
            bookList = bookDao.selectBookBySubjectOrderSaleAsc(id);
        }
        if (bookList.size() == 0) {
            throw new ServiceException(CodeMsg.NON_FIND_SUBJECT);
        } else {
            return checkMaxPage(pageNum,bookList);
        }
    }

    public List<BuyBook> searchBookBySubjectOrderPriceDesc(Integer id,int pageNum) {
        Subject subject = subjectDao.findSubjectBySubjectId(id);
        List<BuyBook> bookList;
        PageHelper.startPage(pageNum,20);
        if(subject.getParentId()==0){
            bookList = bookDao.selectBookByParentSubjectOrderPriceDesc(id);
        }
        else{
            bookList = bookDao.selectBookBySubjectOrderPriceDesc(id);
        }
        if (bookList.size() == 0) {
            throw new ServiceException(CodeMsg.NON_FIND_SUBJECT);
        } else {
            return checkMaxPage(pageNum,bookList);
        }
    }

    public List<BuyBook> searchBookBySubjectOrderPriceAsc(Integer id,int pageNum) {
        Subject subject = subjectDao.findSubjectBySubjectId(id);
        List<BuyBook> bookList;
        PageHelper.startPage(pageNum,20);
        if(subject.getParentId()==0){
            bookList = bookDao.selectBookByParentSubjectOrderPriceAsc(id);
        }
        else{
            bookList = bookDao.selectBookBySubjectOrderPriceAsc(id);
        }
        if (bookList.size() == 0) {
            throw new ServiceException(CodeMsg.NON_FIND_SUBJECT);
        } else {
            return checkMaxPage(pageNum,bookList);
        }
    }

    // 用EasyExcel进行批量导入
    public void addBookBatch(MultipartFile file, BookService bookService, BookReserveService conditionService) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            EasyExcel.read(inputStream, BookExcelData.class, new BookExcelListener(bookService,conditionService)).sheet().doRead();
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (IOException e) {
//            e.printStackTrace();
            System.out.println("读写错误");
        }

    }

    // 根据标题找到所属分类的一二级id，再Excel添加分类时用到
    public Subject findSubjectByTitle(String title) {
        return subjectService.findSubjectByTitle(title);
    }

    // Excel批量添加用到
    public void insert(BuyBook book) {
        bookDao.insert(book);
    }

    // 直接根据ISBN从数据库中查找，不用调用api
    public BuyBook DirectQueryBookFromDataBase(String isbn) {
        return bookDao.selectBookByISBNAndReserve(isbn);
    }

    // 调用易源Api直接查询书本的属性
    public BuyBook getBookDetailsFromApi(String isbn) {

//        BuyBook newBook = bookDao.selectBookByISBN(isbn);
//        if (newBook!=null){
//            throw new ServiceException(CodeMsg.REPEATED_BOOK);
//        }
//
//
//        String res = new ShowApiRequest(url1, appid, secret)
//                .addTextPara("isbn", isbn)
//                .post();
//        JSONObject resJson = JSON.parseObject(res);
//        if (resJson.get("showapi_res_code").equals(0)) {
//            //请求成功
//            if (!resJson.getJSONObject("showapi_res_body").getString("ret_code").equals("0")) {
//                return getBookDetailsFromApi2(isbn);
//            }
//        }
//        BuyBook book = new BuyBook();
////        封装属性
//        JSONObject resBook = resJson.getJSONObject("showapi_res_body").getJSONArray("datas").getJSONObject(0);
//        book.setIsbn(isbn);
//        book.setSeries(resBook.getString("series"));
//        book.setTitle(resBook.getString("title"));
//        book.setImg(resBook.getString("img"));
//        book.setSmallImg(resBook.getString("smallimg"));
//        book.setPrice(resBook.getString("price"));
//        book.setAuthor(resBook.getString("author"));
//        book.setPublisher(resBook.getString("publisher"));
//        book.setPubDate(resBook.getString("pubdate"));
//        book.setPubPlace(resBook.getString("pubplace"));
//        book.setBinding(resBook.getString("binding"));
//        book.setGenus(resBook.getString("genus"));
//        book.setFormat(resBook.getString("format"));
//        book.setPage(resBook.getString("page"));
//        book.setWordNum(resBook.getString("wordnum"));
//        book.setEdition(resBook.getString("edition"));
//        book.setYinci(resBook.getString("yinci"));
//        book.setPaper(resBook.getString("paper"));
//        book.setLanguage(resBook.getString("language"));
//        book.setKeyword(resBook.getString("keyword"));
//        book.setBookCatalog(resBook.getString("bookcatalog"));
//        book.setGist(resBook.getString("gist"));
//        book.setCipTxt(resBook.getString("ciptxt"));
//        book.setSearchTime(1);
//        book.setCreateTime(new Date());
//        book.setSaleVolume(0);
////        不是对象不能用这个类
////        BeanUtils.copyProperties(resBook, book);
////        book.setSearchTime(1);

        return null;

    }

    public BuyBook getBookDetailsFromApi2(String isbn) {

        String res = new ShowApiRequest(url2, appid, secret)
                .addTextPara("isbn", isbn)
                .post();
        JSONObject resJson = JSON.parseObject(res);
        if (resJson.get("showapi_res_code").equals(0)) {
            //请求成功
            if (!resJson.getJSONObject("showapi_res_body").getString("ret_code").equals("0")) {
                String remark = resJson.getJSONObject("showapi_res_body").getString("remark");
                throw new ServiceException(CodeMsg.SHOWAPI_ERROR.fillArgs(remark));
            }
        }
        BuyBook book = new BuyBook();
//        封装属性
        JSONObject resBook = resJson.getJSONObject("showapi_res_body").getJSONObject("data");
        book.setIsbn(isbn);
        book.setTitle(resBook.getString("title"));
        book.setImg(resBook.getString("img"));
        book.setPrice(resBook.getString("price"));
        book.setAuthor(resBook.getString("author"));
        book.setPublisher(resBook.getString("publisher"));
        book.setPubDate(resBook.getString("pubdate"));
        book.setBinding(resBook.getString("binding"));
        book.setFormat(resBook.getString("format"));
        book.setPage(resBook.getString("page"));
        book.setEdition(resBook.getString("edition"));
        book.setPaper(resBook.getString("paper"));
        book.setGist(resBook.getString("gist"));
        book.setSearchTime(1);
        book.setCreateTime(new Date());
        book.setSaleVolume(0);
//        不是对象不能用这个类
//        BeanUtils.copyProperties(resBook, book);
//        book.setSearchTime(1);

        return book;

    }

    //获取最新上架书籍
    public List<BuyBook> searchBookByCreateTime(int pageNum){
        PageHelper.startPage(pageNum,20);
        List<BuyBook> books = bookDao.selectBookByCreateTime();
        return checkMaxPage(pageNum,books);
    }

    //获取所有热销榜单书籍
    public List<Book> searchAllHotSale(int pageNum){
        PageHelper.startPage(pageNum,20);
        List<Book> books = hotSaleDao.selectAll();
        PageInfo pageInfo = new PageInfo(books);
        if(pageNum>pageInfo.getPages()){
            throw new ServiceException(CodeMsg.MAX_PAGES.fillArgs("没有更多内容"));
        }
        return books;
    }

    private List<BuyBook> checkMaxPage(int pageNum,List<BuyBook> books){
        PageInfo pageInfo = new PageInfo(books);
        if(pageNum>pageInfo.getPages()){
            throw new ServiceException(CodeMsg.MAX_PAGES.fillArgs("没有更多内容"));
        }
        return books;
    }


    private void checkBooksIsEmpty(List<BuyBook> books){
        if(books.isEmpty())
            throw new ServiceException(CodeMsg.NOT_BUY_BOOK.fillArgs("书店没有此书"));
    }

    public void completeOrderIncrease(Order order){

        List<OrderBook> books = order.getBooks();

        for (OrderBook orderBook : books){
            BuyBook book = bookDao.selectBookByISBNAndStore(orderBook.getIsbn(), order.getStoreId());
            book.setSaleVolume(orderBook.getNum());
            bookDao.IncreaseSaleVolume(book);
        }
    }

}